package com.qs.javame.thread.daemon.threadlocal;

import java.util.concurrent.TimeUnit;

/**
 * 测试：ThreadLocal
 */
public class TestThreadLocal {

    public static void main(String[] args) throws InterruptedException {
        Profiler.begin();
        TimeUnit.SECONDS.sleep(3);
        System.out.println("-->>cost: " + Profiler.end());
    }

    /**
     * 测试：使用ThreadLocal实现耗时统计工具类；
     */
    private static class Profiler {
        //使用ThreadLocal存储当前时间，每个线程单独存储自己使用的变量值
        private static final ThreadLocal<Long> TIME_THREADLOCAL = new ThreadLocal<Long>() {
            @Override
            protected Long initialValue() {
                return System.currentTimeMillis();
            }
        };

        //设置开始时间点
        public static final void begin() {
            TIME_THREADLOCAL.set(System.currentTimeMillis());
        }

        //计算程序耗时
        public static final long end() {
            return System.currentTimeMillis() - TIME_THREADLOCAL.get();
        }
    }
}



